package org.apache.mina.example.lily.service;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class ClientEncoder extends ProtocolEncoderAdapter{

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		String str = JSON.toJSONString(message, SerializerFeature.BeanToArray,SerializerFeature.SortField);
		System.out.println(str);
		byte[] data = str.getBytes();
		IoBuffer buffer = IoBuffer.allocate(data.length+4).putInt(data.length).put(data);
		buffer.flip();
		out.write(buffer);
	}

}
